import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/entity/driver_info_entity.dart';
import 'package:nyh_motorcade_app/entity/motorcade_entity.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/pages/driver_manage/driver_manage_controller.dart';
import 'package:nyh_motorcade_app/routes/routes.dart';
import 'package:nyh_motorcade_app/utils/sp_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class BindDriverController extends GetxController {
  RefreshController refreshController = RefreshController();
  MultiState multiState = MultiState.loading;
  ScrollController scrollController = ScrollController();

  String driverType = "";
  String driverTypeName = "";
  String motorcadeId = "";
  String motorcadeName = "";

  List<DriverType> driverTypeList = [];
  List<MotorcadeEntity> motorcadeList = [];
  bool showDriverTypeMenu = false;
  bool showMotorcadeMenu = false;

  int page = 1;
  List<DriverInfoItem> driverInfoList = [];

  //卡绑司机或者车辆绑司机(不可筛选车队)
  String bindType = "";

  //cardId或者vehicleId
  String sourceId = "";

  @override
  void onInit() {
    super.onInit();
    initDriverTypeList();
  }

  @override
  void onReady() {
    super.onReady();
    dynamic arguments = Get.arguments;
    if (arguments != null && arguments is Map) {
      bindType = arguments[Constant.PARAM_TYPE];
      sourceId = arguments[Constant.PARAM_SOURCE_ID];
      //车辆绑司机需要车队ID
      if (bindType == Constant.VEHICLE_BIND_DRIVER) {
        motorcadeId = arguments[Constant.PARAM_MOTORCADE_ID];
      }
      getDriverInfoList();
    }
  }

  Future<void> onRefresh() async {
    page = 1;
    getDriverInfoList();
  }

  Future<void> onLoading() async {
    getDriverInfoList();
  }

  void onRetry() {
    multiState = MultiState.loading;
    update();
    getDriverInfoList();
  }

  Future<void> goToAddDriverPage() async {
    dynamic data = await Get.toNamed(Routes.addDriver, arguments: {Constant.PARAM_IS_RETURN: true});
    if (data != null) {
      page = 1;
      multiState = MultiState.loading;
      update();
      getDriverInfoList();
    }
  }

  Future<void> onConfirm() async {
    List<String> driverIdList = getSelectDriverIdList();
    if (driverIdList.isEmpty) {
      return;
    }
    httpManager.post(
      Get.context,
      bindType == Constant.CARD_BIND_DRIVER ? HttpAddress.CARD_BIND_DRIVER : HttpAddress.VEHICLE_BIND_DRIVER,
      bindType == Constant.CARD_BIND_DRIVER ? {"cardId": sourceId, "driverIds": driverIdList} : {"vehicleId": sourceId, "driverIds": driverIdList},
      isToast: true,
      isLoadingDialog: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          return;
        }
        if (data is bool) {
          if (!data) {
            ToastUtils.toast("绑定失败");
            return;
          }
          ToastUtils.toast("绑定成功");
          Get.back(result: {});
        }
      },
    );
  }

  List<String> getSelectDriverIdList() {
    List<String> list = [];
    if (driverInfoList.isEmpty) {
      return list;
    }
    driverInfoList.forEach((element) {
      if ((element.isSelect ?? false)) {
        list.add(element.id ?? "");
      }
    });
    return list;
  }

  Future<void> getDriverInfoList() async {
    httpManager.post(
      Get.context,
      bindType == Constant.CARD_BIND_DRIVER ? HttpAddress.GET_CARD_BIND_DRIVER_INFO_LIST : HttpAddress.GET_VEHICLE_BIND_DRIVER_INFO_LIST,
      bindType == Constant.CARD_BIND_DRIVER
          ? {
              "superId": await SPUtils.getString(SPUtils.COMPANY_ID),
              "cardId": sourceId,
              "belongingType": driverType.isNotEmpty ? driverType : null,
              "motorcadeId": motorcadeId.isNotEmpty ? motorcadeId : null,
            }
          : {
              "superId": await SPUtils.getString(SPUtils.COMPANY_ID),
              "motorcadeId": motorcadeId,
              "vehicleId": sourceId,
              "belongingType": driverType.isNotEmpty ? driverType : null,
            },
      headers: {"page": page, "limit": 10},
      isToast: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          if (refreshController.isRefresh) {
            refreshController.refreshFailed();
          } else {
            refreshController.loadFailed();
          }
          if (page == 1) {
            multiState = MultiState.fail;
          }
          update();
          return;
        }
        if (data is List) {
          List<DriverInfoItem> list = data.map((element) {
            return DriverInfoItem().fromJson((element as Map<String, dynamic>));
          }).toList();
          if (list.isNotEmpty) {
            multiState = MultiState.success;
            if (refreshController.isRefresh) {
              driverInfoList.clear();
              refreshController.refreshCompleted();
              if (scrollController.hasClients) {
                scrollController.jumpTo(0);
              }
            } else {
              if (list.length >= 10 || page == 1) {
                refreshController.loadComplete();
              } else {
                refreshController.loadNoData();
              }
            }
            if (page == 1) {
              driverInfoList.clear();
            }
            driverInfoList.addAll(list);
            page++;
          } else {
            if (refreshController.isRefresh) {
              refreshController.refreshCompleted();
            } else {
              refreshController.loadNoData();
            }
            if (page == 1) {
              multiState = MultiState.empty;
            }
          }
          update();
        }
      },
      onFail: (code, msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        if (page == 1) {
          multiState = MultiState.fail;
        }
        update();
      },
      onError: (msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        } else {
          refreshController.loadFailed();
        }
        if (page == 1) {
          multiState = MultiState.error;
        }
        update();
      },
    );
  }

  Future<List<MotorcadeEntity>> getMotorcadeList() async {
    if (motorcadeList.isNotEmpty) {
      return motorcadeList;
    }
    HttpResult httpResult = await httpManager.post(Get.context, HttpAddress.GET_MOTORCADE_FILTER_LIST, {"superId": await SPUtils.getString(SPUtils.COMPANY_ID)}, isToast: true, isLoadingDialog: true);
    dynamic data = httpResult.data;
    if (data == null) {
      return [];
    }
    if (data is List) {
      motorcadeList = data.map((element) {
        return MotorcadeEntity().fromJson((element as Map<String, dynamic>));
      }).toList();
      MotorcadeEntity motorcadeEntity = MotorcadeEntity();
      motorcadeEntity.id = "";
      motorcadeEntity.name = "全部";
      motorcadeList.insert(0, motorcadeEntity);
      return motorcadeList;
    }
    return [];
  }

  void setSelectMotorcade(int? value) {
    showMotorcadeMenu = false;
    if (value != null) {
      String id = motorcadeList[value].id ?? "";
      motorcadeName = value != 0 ? (motorcadeList[value].name ?? "") : "全部车队";
      if (motorcadeId != id) {
        motorcadeId = id;
        page = 1;
        multiState = MultiState.loading;
        getDriverInfoList();
      }
    }
    update();
  }

  void setSelectDriverType(int? value) {
    showDriverTypeMenu = false;
    if (value != null) {
      String type = driverTypeList[value].type;
      driverTypeName = value != 0 ? driverTypeList[value].name : "全部归属";
      if (driverType != type) {
        driverType = type;
        page = 1;
        multiState = MultiState.loading;
        getDriverInfoList();
      }
    }
    update();
  }

  void initDriverTypeList() {
    driverTypeList.add(DriverType("全部", ""));
    driverTypeList.add(DriverType("自有", Constant.OWN_DRIVER));
    driverTypeList.add(DriverType("外协", Constant.EXTERNAL_DRIVER));
  }
}
